<template>
  <view class="gomoku-game-container">
    <!-- 头部信息 -->
    <view class="game-header">
      <view class="header-title">五子棋</view>
      <view class="user-info">{{ userName }}</view>
      <view class="game-status">{{ currentPlayer === userId ? '你的回合' : '对方回合' }}</view>
      <view class="game-tip">{{ gameTip }}</view>
    </view>

    <!-- 游戏区域 -->
    <view class="game-area">
      <h2 class="game-title"><i class="fa fa-circle-o"></i> 五子棋对战</h2>

      <!-- 玩家列表 -->
      <view class="player-list">
        <view class="player-card" :class="{ 'current': currentPlayer === players[0]?.user_id }">{{ players[0]?.user_name || '等待加入...' }}
          <view class="piece-type"><i class="fa fa-circle-o"></i></view>
        </view>
        <view class="player-card" :class="{ 'current': currentPlayer === players[1]?.user_id }">{{ players[1]?.user_name || '等待加入...' }}
          <view class="piece-type"><i class="fa fa-times"></i></view>
        </view>
      </view>

      <!-- 游戏棋盘 -->
      <view class="game-board">
        <canvas canvas-id="gomokuCanvas" class="game-canvas" @tap="handleCanvasTap"></canvas>
      </view>

      <!-- 控制按钮 -->
      <view class="control-buttons">
        <button @tap="restartGame" class="restart-btn">重新开始</button>
        <button @tap="toggleReadyStatus" class="ready-btn">{{ isReady ? '取消准备' : '准备' }}</button>
        <button @tap="backToLobby" class="back-btn">返回大厅</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, reactive } from 'vue';
import { useRouter } from 'vue-router';

// 路由实例
const router = useRouter();

// 游戏状态
const gameState = reactive({
  board: [],
  rows: 15,
  cols: 15,
  cellSize: 24,
  winner: null,
  gameOver: false
});

// 响应式变量
const userId = ref('');
const userName = ref('');
const roomId = ref('');
const players = ref([]);
const isReady = ref(false);
const currentPlayer = ref('');
const gameTip = ref('等待玩家加入...');
let ws = null;

/**
 * 初始化棋盘
 */
function initBoard() {
  gameState.board = [];
  gameState.winner = null;
  gameState.gameOver = false;
  currentPlayer.value = players.value[0]?.user_id || '';
  gameTip.value = currentPlayer.value === userId.value ? '你的回合' : '对方回合';

  // 创建空棋盘
  for (let i = 0; i < gameState.rows; i++) {
    gameState.board[i] = [];
    for (let j = 0; j < gameState.cols; j++) {
      gameState.board[i][j] = null; // null: 空, 'black': 黑棋, 'white': 白棋
    }
  }

  renderBoard();
}

/**
 * 渲染棋盘
 */
function renderBoard() {
  const ctx = uni.createCanvasContext('gomokuCanvas');
  const canvasWidth = gameState.cols * gameState.cellSize;
  const canvasHeight = gameState.rows * gameState.cellSize;

  // 清除画布
  ctx.clearRect(0, 0, canvasWidth, canvasHeight);

  // 绘制棋盘背景
  ctx.setFillStyle('#e6c384');
  ctx.fillRect(0, 0, canvasWidth, canvasHeight);

  // 绘制网格线
  ctx.setStrokeStyle('#000000');
  ctx.setLineWidth(1);

  // 绘制横线
  for (let i = 0; i < gameState.rows; i++) {
    ctx.beginPath();
    ctx.moveTo(gameState.cellSize / 2, i * gameState.cellSize + gameState.cellSize / 2);
    ctx.lineTo((gameState.cols - 1) * gameState.cellSize + gameState.cellSize / 2, i * gameState.cellSize + gameState.cellSize / 2);
    ctx.stroke();
  }

  // 绘制竖线
  for (let j = 0; j < gameState.cols; j++) {
    ctx.beginPath();
    ctx.moveTo(j * gameState.cellSize + gameState.cellSize / 2, gameState.cellSize / 2);
    ctx.lineTo(j * gameState.cellSize + gameState.cellSize / 2, (gameState.rows - 1) * gameState.cellSize + gameState.cellSize / 2);
    ctx.stroke();
  }

  // 绘制天元和星位
  const starPoints = [
    { x: 3, y: 3 }, { x: 3, y: 7 }, { x: 3, y: 11 },
    { x: 7, y: 3 }, { x: 7, y: 7 }, { x: 7, y: 11 },
    { x: 11, y: 3 }, { x: 11, y: 7 }, { x: 11, y: 11 }
  ];

  starPoints.forEach(point => {
    ctx.setFillStyle('#000000');
    ctx.beginPath();
    ctx.arc(
      point.x * gameState.cellSize + gameState.cellSize / 2,
      point.y * gameState.cellSize + gameState.cellSize / 2,
      4,
      0, 2 * Math.PI
    );
    ctx.fill();
  });

  // 绘制棋子
  for (let i = 0; i < gameState.rows; i++) {
    for (let j = 0; j < gameState.cols; j++) {
      if (gameState.board[i][j]) {
        const isBlack = gameState.board[i][j] === 'black';

        // 绘制棋子
        ctx.setFillStyle(isBlack ? '#000000' : '#ffffff');
        ctx.beginPath();
        ctx.arc(
          j * gameState.cellSize + gameState.cellSize / 2,
          i * gameState.cellSize + gameState.cellSize / 2,
          gameState.cellSize / 2 - 3,
          0, 2 * Math.PI
        );
        ctx.fill();

        // 绘制棋子边框
        ctx.setStrokeStyle('#000000');
        ctx.setLineWidth(1);
        ctx.stroke();

        // 标记最后一步
        if (i === lastMove.i && j === lastMove.j) {
          ctx.setFillStyle('#ff0000');
          ctx.beginPath();
          ctx.arc(
            j * gameState.cellSize + gameState.cellSize / 2,
            i * gameState.cellSize + gameState.cellSize / 2,
            3,
            0, 2 * Math.PI
          );
          ctx.fill();
        }
      }
    }
  }

  // 绘制游戏结果
  if (gameState.gameOver && gameState.winner) {
    ctx.setFillStyle('rgba(0, 0, 0, 0.5)');
    ctx.fillRect(0, canvasHeight / 2 - 30, canvasWidth, 60);

    ctx.setFillStyle('#ffffff');
    ctx.setFontSize(24);
    ctx.setTextAlign('center');
    ctx.setTextBaseline('middle');

    const winnerName = players.value.find(p => p.user_id === gameState.winner)?.user_name || '玩家';
    ctx.fillText(`${winnerName} 获胜！`, canvasWidth / 2, canvasHeight / 2);
  }

  ctx.draw();
}

// 记录最后一步
const lastMove = ref({ i: -1, j: -1 });

/**
 * 处理棋盘点击
 */
function handleCanvasTap(e) {
  if (gameState.gameOver || currentPlayer.value !== userId.value || !isReady.value) {
    return;
  }

  const { x, y } = e.detail;
  const canvasRect = uni.createSelectorQuery().select('.game-canvas').boundingClientRect();

  canvasRect.exec(rects => {
    if (rects && rects[0]) {
      const rect = rects[0];
      const canvasX = x - rect.left;
      const canvasY = y - rect.top;

      // 计算点击的行列
      const j = Math.round((canvasX - gameState.cellSize / 2) / gameState.cellSize);
      const i = Math.round((canvasY - gameState.cellSize / 2) / gameState.cellSize);

      // 检查是否在棋盘范围内且为空
      if (i >= 0 && i < gameState.rows && j >= 0 && j < gameState.cols && !gameState.board[i][j]) {
        // 落子
        const pieceType = currentPlayer.value === players.value[0]?.user_id ? 'black' : 'white';
        gameState.board[i][j] = pieceType;
        lastMove.value = { i, j };

        // 检查是否获胜
        if (checkWin(i, j, pieceType)) {
          gameState.winner = currentPlayer.value;
          gameState.gameOver = true;
          gameTip.value = `${players.value.find(p => p.user_id === currentPlayer.value)?.user_name} 获胜！`;
        } else {
          // 切换玩家
          currentPlayer.value = currentPlayer.value === players.value[0]?.user_id ? players.value[1]?.user_id : players.value[0]?.user_id;
          gameTip.value = currentPlayer.value === userId.value ? '你的回合' : '对方回合';
        }

        // 渲染棋盘
        renderBoard();

        // 发送落子信息到服务器 (实际应用中需要实现)
        // sendMove(i, j, pieceType);
      }
    }
  });
}

/**
 * 检查是否获胜
 */
function checkWin(i, j, pieceType) {
  const directions = [
    [0, 1],  // 水平
    [1, 0],  // 垂直
    [1, 1],  // 对角线
    [1, -1]  // 反对角线
  ];

  for (const [dx, dy] of directions) {
    let count = 1;  // 当前位置已经有一个棋子

    // 正向检查
    for (let step = 1; step <= 4; step++) {
      const ni = i + step * dx;
      const nj = j + step * dy;

      if (ni >= 0 && ni < gameState.rows && nj >= 0 && nj < gameState.cols && gameState.board[ni][nj] === pieceType) {
        count++;
      } else {
        break;
      }
    }

    // 反向检查
    for (let step = 1; step <= 4; step++) {
      const ni = i - step * dx;
      const nj = j - step * dy;

      if (ni >= 0 && ni < gameState.rows && nj >= 0 && nj < gameState.cols && gameState.board[ni][nj] === pieceType) {
        count++;
      } else {
        break;
      }
    }

    if (count >= 5) {
      return true;
    }
  }

  return false;
}

/**
 * 重新开始游戏
 */
function restartGame() {
  initBoard();
}

/**
 * 切换准备状态
 */
function toggleReadyStatus() {
  isReady.value = !isReady.value;
  gameTip.value = isReady.value ? '已准备' : '未准备';
  // 这里应该发送WebSocket消息通知其他玩家
}

/**
 * 返回游戏大厅
 */
function backToLobby() {
  // 清理游戏资源
  if (ws) {
    try {
      ws.close();
    }
    catch (e) {}
    ws = null;
  }

  // 导航回游戏空间
  router.push('/pages/games/index');
}

// 生命周期钩子
onMounted(() => {
  // 获取用户信息和房间ID (实际应用中应该从登录状态或URL参数获取)
  // 这里只是示例，实际项目中需要替换为真实的获取方式
  userId.value = 'user123';
  userName.value = '玩家1';
  roomId.value = 'room789';

  // 初始化玩家列表
  players.value = [
    { user_id: userId.value, user_name: userName.value, ready: false },
    { user_id: 'user456', user_name: '等待加入...', ready: false }
  ];

  // 初始化棋盘
  initBoard();
});

onUnmounted(() => {
  // 清理游戏资源
  if (ws) {
    try {
      ws.close();
    }
    catch (e) {}
    ws = null;
  }
});
</script>

<style scoped>
.gomoku-game-container {
  padding: 16px;
  min-height: 100vh;
  background: linear-gradient(135deg, #e0e7ff 0%, #f8fafc 100%);
}

.game-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #6366f1;
}

.user-info {
  font-size: 14px;
  color: #1f2937;
}

.game-status {
  font-size: 14px;
  font-weight: bold;
  color: #6366f1;
}

.game-tip {
  font-size: 14px;
  color: #6b7280;
}

.game-area {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 32px rgba(99, 102, 241, 0.2);
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.game-title {
  font-size: 18px;
  font-weight: bold;
  color: #4f46e5;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.game-title i {
  margin-right: 8px;
}

.player-list {
  display: flex;
  justify-content: space-between;
  width: 100%;
  max-width: 320px;
  margin-bottom: 16px;
  gap: 10px;
}

.player-card {
  flex: 1;
  background: #f3f4f6;
  border-radius: 10px;
  padding: 10px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.player-card.current {
  border: 2px solid #6366f1;
  background: #f0f4ff;
}

.piece-type {
  margin-top: 4px;
  font-size: 16px;
}

.game-board {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.game-canvas {
  width: 360px;
  height: 360px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(99, 102, 241, 0.1);
}

.control-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  justify-content: center;
}

.restart-btn, .ready-btn, .back-btn {
  padding: 8px 16px;
  border-radius: 50px;
  font-weight: bold;
  border: none;
  cursor: pointer;
  transition: all 0.2s;
}

.restart-btn {
  background: linear-gradient(90deg, #6366f1 0%, #818cf8 100%);
  color: white;
}

.ready-btn {
  background: #f3f4f6;
  color: #1f2937;
}

.back-btn {
  background: #fee2e2;
  color: #dc2626;
}

.restart-btn:hover {
  opacity: 0.9;
  transform: scale(1.05);
}
</style>